<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/mine/mdxqBg.png" mode="widthFix"></image>
		</view>
		<cusHeaderVue titleContent="门店详情" :showBack="true"></cusHeaderVue>
		<scroll-view scroll-y="true"
			:style="{height:`calc(100vh - ${scrollerHeight} - 80rpx)`,paddingTop:`calc(${scrollerHeight} + 80rpx)`}">
			<view class="contBox">
				<view class="listLi">
					<view class="listTag">
						{{shopXqDetail.level}}
					</view>
					<view class="listName">
						{{shopXqDetail.name}}
					</view>

					<view class="listAddress">
						<image src="/static/home/didian.png" mode=""></image>
						{{ shopXqDetail.juli || '计算中...' }}
						<view class="listAddressName">
							{{shopXqDetail.address}}
						</view>
					</view>
					<view class="listTime">
						<view class="listTimeName" @click="selectMonth">
							{{selectedMonth}}
						</view>
						<u-icon name="arrow-down-fill" color="#F79F31" size="10"></u-icon>
					</view>
				</view>
				<view class="box">
					<view class="boxTop">
						<view class="boxTit">
							进销存分析
						</view>
						<view class="boxRight">
							单位:元
						</view>
					</view>
					<view class="boxMb">
						<view class="boxMbOne">
							<image src="/static/mine/ljgj.png" mode=""></image>
							<view class="boxMbOneCont">
								<view class="boxMbName">
									累计购进
								</view>
								<view class="boxMbNum">
									{{shopXqDetail.dxProductYoYRespVO.currentPeriodPurchaseTotal}}
								</view>
								<view class="boxMbNumBfb">
									同比<text>{{shopXqDetail.dxProductYoYRespVO.purchaseYoyRate}}</text>
								</view>
							</view>
						</view>
						<view class="boxMbOne">
							<image src="/static/mine/ljxsBg.png" mode=""></image>
							<view class="boxMbOneCont">
								<view class="boxMbName">
									累计销售
								</view>
								<view class="boxMbNum">
									{{shopXqDetail.dxProductYoYRespVO.currentPeriodSaleTotal}}
								</view>
								<view class="boxMbNumBfb">
									同比<text>{{shopXqDetail.dxProductYoYRespVO.salYoyRate}}</text>
								</view>
							</view>
						</view>
						<view class="boxMbZj">
							<!-- <view class="boxMbZjLi">
								<view class="boxMbZjName">
									库存
								</view>
								<view class="boxMbZjNum">
									2,361
								</view>
							</view> -->

							<!-- <view class="boxMbZjLi" style="margin-top: 11rpx;">
								<view class="boxMbZjName">
									周转天数
								</view>
								<view class="boxMbZjNum">
									8天
								</view>
							</view> -->
						</view>
					</view>
					<view v-if="shopXqDetail.dxProductYoYRespVOS.length  " class="analyseLi"
						v-for="(itemn,index) in shopXqDetail.dxProductYoYRespVOS" :key="index">
						<view class="analyseTit">
							{{itemn.productName}}
						</view>
						<view class="analyseLiBox">
							<view class="analyseBoxLi">
								<view class="analyseLiName">
									累计购进
								</view>
								<view class="analyseLiNum">
									{{itemn.currentPurchaseMoney}}
								</view>
							</view>
							<view class="analyseBoxLi">
								<view class="analyseLiName">
									购进同比
								</view>
								<view class="analyseLiNum analyseLiNumRed">
									{{itemn.purchaseYoYRateFormatted}}
								</view>
							</view>
							<view class="analyseBoxLi">
								<view class="analyseLiName">
									累计销售
								</view>
								<view class="analyseLiNum">
									{{itemn.currentSaleMoney}}
								</view>
							</view>
							<view class="analyseBoxLi">
								<view class="analyseLiName">
									销售同比
								</view>
								<view class="analyseLiNum analyseLiNumRed">
									{{itemn.saleYoYRateFormatted}}
								</view>
							</view>
							<!-- 	<view class="analyseBoxLi">
								<view class="analyseLiName">
									库存
								</view>
								<view class="analyseLiNum">
									14,107
								</view>
							</view>
							<view class="analyseBoxLi">
								<view class="analyseLiName">
									周转天数
								</view>
								<view class="analyseLiNum analyseLiNumRed">
									8天
								</view>
							</view> -->
						</view>
					</view>
				</view>
				<view class="box">
					<view class="boxTop">
						<view class="boxTit">
							物料投放情况
						</view>
					</view>
					<view v-if="shopXqDetail.dxMaterialsDeliveryDOS.length" class="materialCollection"
						v-for="(item,index) in shopXqDetail.dxMaterialsDeliveryDOS" :key="index">
						<view class="materialCollectionTop">
							<view class="materialCollectionName">
								{{item.name}}
							</view>
						</view>
						<view class="materialCollectionBox">
							<!-- <view class="materialCollectionLi">
								领取数量<text>5</text>
							</view> -->
							<view class="materialCollectionLi">
								投放数量<text>{{item.num}}</text>
							</view>
							<view class="materialCollectionLi">
								投放日期<text>{{item.createTimeStr}}</text>
							</view>
						</view>

					</view>
					<view v-else class="empty-data">
						<text class="empty-text">暂无数据</text>
					</view>
				</view>
				<view class="box">
					<view class="boxTop">
						<view class="boxTit">
							打卡情况
							<view class="boxNumBox">
								共计<text>{{ shopXqDetail.shopCheckDOS.length }}</text>次
							</view>
						</view>
					</view>
					<view v-if="shopXqDetail" class="materialCollection materialCollectionJob"
						v-for="(item,index) in shopXqDetail.shopCheckDOS" :key="index">
						<view class="materialCollectionTop">
							<view class="materialCollectionName">
								{{item.createTimeStr}}
							</view>
						</view>
						<view class="materialCollectionBox">
							<view class="materialCollectionLi" style="width: 100%;">
								打卡人<text>{{item.nickname}}</text>
							</view>
						</view>

					</view>
					<view v-else class="empty-data">
						<text class="empty-text">暂无数据</text>
					</view>
				</view>
				<view class="box" v-if="shopXqDetail">
					<view class="boxTop">
						<view class="boxTit">
							培训记录
						</view>
					</view>
					<view v-if="shopXqDetail.dxCursesSubmitDO.length" class="materialCollection materialCollectionJob"
						v-for="(item,index) in shopXqDetail.dxCursesSubmitDO" :key="index">
						<view class="materialCollectionTop">
							<view class="materialCollectionName">
								{{item.title}}
							</view>
						</view>
						<view class="materialCollectionBox">
							<view class="materialCollectionLi" style="width: 100%;"
								@click="toUrl('/pages/index/homeworkDetails?id='+item.id)">
								<view class="materialCollectionLiName">
									提交内容:
								</view>
								<text  style="color: #3A66F3;">{{item.content}}</text>
							</view>
							<view class="materialCollectionLi">
								<view class="materialCollectionLiName">
									日期
								</view>
								<text>{{item.createTimeStr}}</text>
							</view>
							<view class="materialCollectionLi">
								<view class="materialCollectionLiName">
									培训人
								</view>
								<text>{{item.nickname}}</text>
							</view>
							
							<view class="materialCollectionLi media-buttons" style="width: 100%;">
								<!-- 文件下载按钮 -->
								<view v-if="item.files && item.files.length > 0" class="media-btn download-btn"
									@click="viewFile(item.files)">
									<image src="/static/mine/cl.png" mode="aspectFit" class="media-icon"></image>
									<text>文件下载</text>
								</view>
								<!-- 图片查看按钮 -->
								<view v-if="item.images && item.images.length > 0" class="media-btn image-btn"
									@click="viewImage(item.images)">
									<image src="/static/home/fujian.png" mode="aspectFit" class="media-icon">
									</image>
									<text>图片查看</text>
								</view>
								<!-- 视频查看按钮 -->
								<view v-if="item.videos && item.videos.length > 0" class="media-btn video-btn"
									@click="viewVideo(item.videos)">
									<image src="/static/home/fpl.png" mode="aspectFit" class="media-icon"></image>
									<text>视频查看</text>
								</view>
							</view>
							
						</view>
					</view>
					<view v-else class="empty-data">
						<text class="empty-text">暂无数据</text>
					</view>
				</view>
			</view>
		</scroll-view>

		<MonthPickerPopup ref="monthPickerRef" @confirm="onMonthConfirm" @cancel="onMonthCancel" />

	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app';

	import {
		ref
	} from 'vue';
	import MonthPickerPopup from '@/components/MonthPickerPopup.vue';
	import cusHeaderVue from '@/components/cus-header.vue';

	import {
		GETShopDetail
	} from '@/api/interface.js';
	import {
		formatDate,
		timestampToYearMonthDay
	} from '@/utils/date.js'
	import {
		getDistanceTo
	} from '@/utils/distance.js';







	const xqId = ref('');
	const scrollerHeight = ref('');
	const selectedMonth = ref('');
	const storeList = ref([]);
	const monthPickerRef = ref(null);
	const shopXqDetail = ref({});


	const ljgj = ref(0);
	const ljxs = ref(0);

	const ljgjMon = ref(0);
	const ljxsMon = ref(0);

	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}

	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	}

	onLoad((item) => {
		console.log(item);
		xqId.value = item.id;
		getBarHeight();
		initDefaultMonth();
	});



	// 初始化默认月份
	const initDefaultMonth = () => {
		const now = new Date();
		const year = now.getFullYear();
		const month = now.getMonth() + 1;
		selectedMonth.value = `${year}年${month}月`;
		getDetailForId();
	};
	const getDetailForId = () => {

		GETShopDetail({
			shopId: xqId.value,
			dateStr: formatDate(selectedMonth.value)
		}).then(res => {
			// 👇 调用工具函数计算距离
			const lat = res.data.latitude || 32;
			const lon = res.data.longitude || 118;

			getDistanceTo(lat, lon).then(dist => {
				shopXqDetail.value['juli'] = dist;
			});
			console.log(res.data)

			res.data.shopCheckDOS = res.data.shopCheckDOS.map(item => ({
				...item,
				createTimeStr: timestampToYearMonthDay(item.createTime)
			}));

			let ljgj1 = 0;
			let ljxs1 = 0;
			let ljgjMon1 = 0;
			let ljxsMon1 = 0;
			res.data.dxProductYoYRespVOS = res.data.dxProductYoYRespVOS.map(item => ({
				...item,
				ljgj: ljgj1 += item.lastYearSaleMoney,
				ljxs: ljxs1 += item.lastYearPurchaseMoney,
				ljgjMon: ljgjMon1 += item.currentPurchaseMoney,
				ljxsMon: ljxsMon1 += item.currentSaleMoney,
				createTimeStr: timestampToYearMonthDay(item.createTime)
			}));

			ljgj.value = ljgj1;
			ljxs.value = ljxs1;
			ljgjMon.value = ljgj1;
			ljxsMon.value = ljxs1;

			res.data.dxMaterialsDeliveryDOS = res.data.dxMaterialsDeliveryDOS.map(item => ({
				...item,
				createTimeStr: timestampToYearMonthDay(item.createTime)
			}));


			res.data.dxCursesSubmitDO = res.data.dxCursesSubmitDO.map(item => ({
				...item,
				createTimeStr: timestampToYearMonthDay(item.createTime),
				// 对齐 salesRepresentative.vue 的媒体字段映射
				files: item.fileUrl ? [{ url: item.fileUrl }] : [],
				images: item.imageUrl ? item.imageUrl.split(',').map(url => ({ url: url.trim() })) : [],
				videos: item.videoUrl ? [{ url: item.videoUrl }] : []
			}));

			shopXqDetail.value = res.data
		})

	}

	// 打开年月选择器
	const selectMonth = () => {
		monthPickerRef.value.open();
	};

	// 选择确认
	const onMonthConfirm = (month) => {
		console.log(month)
		selectedMonth.value = month;
		getDetailForId();
	};

	// 取消（可选处理）
	const onMonthCancel = () => {
		// 可不处理，或做日志等
	};

	// 文件查看（下载并打开）
	const viewFile = (files) => {
		if (files && files.length > 0) {
			const file = files[0];
			uni.downloadFile({
				url: file.url || file,
				success: (res) => {
					if (res.statusCode === 200) {
						uni.openDocument({
							filePath: res.tempFilePath,
							showMenu: true,
							success: () => {
								console.log('文件打开成功');
							},
							fail: (err) => {
								console.error('文件打开失败:', err);
								uni.showToast({ title: '文件打开失败', icon: 'none' });
							}
						});
					}
				},
				fail: (err) => {
					console.error('文件下载失败:', err);
					uni.showToast({ title: '文件下载失败', icon: 'none' });
				}
			});
		}
	};

	// 图片预览
	const viewImage = (images) => {
		if (images && images.length > 0) {
			const urls = images.map(img => img.url || img);
			uni.previewImage({
				urls,
				current: 0,
				success: () => { console.log('图片预览成功'); },
				fail: (err) => {
					console.error('图片预览失败:', err);
					uni.showToast({ title: '图片预览失败', icon: 'none' });
				}
			});
		}
	};

	// 视频查看（跳转通用视频页）
	const viewVideo = (videos) => {
		if (videos && videos.length > 0) {
			const video = videos[0];
			const src = video.url || video;
			uni.navigateTo({
				url: `/pages/common/videoPlayer?src=${encodeURIComponent(src)}`,
				fail: (err) => {
					console.error('打开视频播放器失败:', err);
					uni.showToast({ title: '请先配置视频播放页面', icon: 'none' });
				}
			});
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
		position: relative;
	}

	.scroll-view {
		width: 100%;
		height: calc(100vh - var(--status-bar-height) - 90rpx);
		padding-top: 90rpx;
		/* 只考虑头部高度，不包括状态栏，因为cusHeaderVue已经处理了状态栏 */
		box-sizing: border-box;
		/* 移除绝对定位，避免与fixed定位的header冲突 */
	}

	.bgColor {
		width: 100%;
		// height: 750rpx;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.contBox {
		// padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);
		padding: 22rpx;
		box-sizing: border-box;

		.listLi {
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			padding: 37rpx 26rpx 24rpx;
			box-sizing: border-box;
			margin-bottom: 20rpx;
			position: relative;

			.listTag {
				position: absolute;
				width: 60rpx;
				height: 40rpx;
				background: url('/static/home/tagYz.png') no-repeat center;
				background-size: 100% 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				right: 0;
				top: 22rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #FFFBF7;
			}

			.listName {
				font-weight: 500;
				font-size: 32.05rpx;
				color: #1C2027;
			}

			.listAddress {
				display: flex;
				align-items: center;
				font-size: 25.64rpx;
				font-weight: 400;
				color: #1C2027;
				margin-top: 14rpx;

				image {
					width: 40.38rpx;
					height: 40.38rpx;
					margin-right: 12rpx;
				}

				.listAddressName {
					font-size: 25.64rpx;
					font-weight: 400;
					color: #7F8494;
					padding-left: 12rpx;
					box-sizing: border-box;
					margin-left: 12rpx;
					border-left: 1rpx solid #7F8494;
				}
			}

			.listTime {
				min-width: 190rpx;
				height: 55rpx;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #ffffff;
				border: 1px solid #f79f31;
				display: inline-flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 17rpx;
				box-sizing: border-box;
				margin-top: 27rpx;
				width: auto;

				.listTimeName {
					color: #f79f31;
					font-weight: 400;
					font-size: 25.64rpx;
					white-space: nowrap;
					line-height: 55rpx;
				}
			}
		}

		.box {
			padding: 36rpx 23rpx;
			box-sizing: border-box;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			margin-bottom: 30rpx;

			.boxTop {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.boxTit {
					
					font-weight: 500;
					font-size: 33.33rpx;
					color: #1C2027;
					display: flex;
					align-items: center;

					.boxNumBox {
						font-weight: 400;
						font-size: 24.36rpx;
						color: #7F8494;
						margin-left: 31rpx;

						text {
							font-size: 26.92rpx;
							font-weight: 400;
							color: #F79F31;
							margin: 0 5rpx;
						}
					}
				}

				.boxRight {
					font-size: 25.64rpx;
					font-weight: 400;
					color: #7F8494;
				}
			}

			.boxMb {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 32rpx;

				.boxMbOne {
					width: 178rpx;
					height: 206rpx;
					border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
					position: relative;

					image {
						width: 100%;
						height: 100%;
						position: absolute;
						top: 0;
						left: 0;
					}

					.boxMbOneCont {
						width: 100%;
						position: absolute;
						top: 66rpx;
						left: 0;

						.boxMbName {
							font-size: 24.36rpx;
							font-weight: 400;
							color: #7F8494;
							text-align: center;
						}

						.boxMbNum {
							font-size: 37.18rpx;
							font-weight: 400;
							color: #222222;
							text-align: center;
						}

						.boxMbNumBfb {
							font-size: 21.79rpx;
							font-weight: 400;
							color: #7F8494;
							text-align: center;

							text {
								font-size: 25.64rpx;
								font-weight: 400;
								color: #FF3F3F;
								margin-left: 7rpx;
							}
						}
					}

				}

				.boxMbTwo {}

				.boxMbZj {
					.boxMbZjLi {
						display: flex;
						align-items: center;
						justify-content: space-between;
						width: 267.31rpx;
						height: 80.77rpx;
						border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
						background: rgba(255, 246, 231, 0.74);
						padding: 0 24rpx 0 29rpx;
						box-sizing: border-box;

						.boxMbZjName {
							font-size: 24.36rpx;
							font-weight: 400;
							color: #7F8494;
						}

						.boxMbZjNum {
							font-size: 33.33rpx;
							font-weight: 400;
							color: #222222;

						}
					}
				}
			}

			.analyseLi {
				width: 100%;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #ffffff;
				margin-top: 24rpx;

				.analyseTit {
					font-weight: 500;
					font-size: 25.64rpx;
					color: #222222;
					padding: 17rpx 21rpx;
					box-sizing: border-box;
					background: #f3f5ff;
				}

				.analyseLiBox {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					padding: 17rpx 21rpx;
					box-sizing: border-box;

					.analyseBoxLi {
						display: flex;
						align-items: center;
						width: 50%;
						margin-bottom: 20rpx;

						.analyseLiName {
							font-weight: 400;
							font-size: 24.36rpx;
							color: #7F8494;
							width: 96rpx;
							text-align: right;
						}

						.analyseLiNum {
							font-size: 25rpx;
							font-weight: 400;
							color: #222222;
							margin-left: 16rpx;
						}

						.analyseLiNumRed {
							font-size: 25rpx;
							font-weight: 400;
							color: #FF3F3F;
						}
					}
				}
			}

			.materialCollection {
				width: 100%;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: linear-gradient(90deg, #fffbf4, #fffefa);
				margin-top: 25rpx;


				.materialCollectionTop {
					padding: 16rpx 0;
					background: linear-gradient(90deg, #fff0d5, #fffefa);

					.materialCollectionName {
						font-weight: 500;
						font-size: 25.64rpx;
						color: #222222;
						// border-left: 5rpx solid #F79F31;
						padding: 0 16rpx;
						box-sizing: border-box;
						position: relative;
					}

					.materialCollectionName::after {
						content: "";
						width: 5.13rpx;
						height: 25rpx;
						background: #f79f31;
						position: absolute;
						left: 0;
						top: 50%;
						transform: translateY(-50%);
					}

				}

				.materialCollectionBox {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					padding: 0 20rpx;
					box-sizing: border-box;

					.materialCollectionLi {
						font-weight: 400;
						font-size: 24.36rpx;
						color: #7F8494;
						width: 50%;
						margin-top: 22rpx;


						display: flex;
						align-items: center;

						.materialCollectionLiName {
							width: 136rpx;
							text-align: right;
						}

						text {
							font-size: 25rpx;
							font-weight: 400;
							color: #222222;
							margin-left: 15rpx;
						}
					}
				}
			}

			.materialCollectionJob {
				background: linear-gradient(90deg, #f1f9ff, #f8fcfe) !important;

				.materialCollectionTop {
					background: linear-gradient(90deg, #ddeffc, #fffefa) !important;

					.materialCollectionName::after {
						background: #5FBAFF !important;
					}
				}
			}

			/* 媒体按钮容器，与销售代表页保持一致 */
			.media-buttons {
				display: flex;
				gap: 40rpx;
				padding-top: 20rpx;
				flex-wrap: wrap;
			}

			.media-btn {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 20rpx 30rpx;
				background: #f5f7fa;
				border-radius: 8rpx;
				transition: all 0.3s ease;
			}

			.media-btn:active {
				background: #e8e8e8;
			}

			.media-icon {
				width: 60rpx;
				height: 60rpx;
				margin-bottom: 10rpx;
			}

			.media-btn text {
				font-size: 24rpx;
				color: #333;
			}

			.materialCollectionLeave {
				background: linear-gradient(90deg, #fff4f4, #ffffff) !important;

				.materialCollectionTop {
					background: linear-gradient(90deg, #ffe2e2, #fffefa) !important;

					.materialCollectionName::after {
						background: #FF5E5E !important;
					}
				}
			}
		}
	}

	.empty-data {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
		/* 可根据需要调整高度 */
		background-color: #ffffff;
		color: #999999;
		font-size: 28rpx;
		text-align: center;

	}

	.empty-text {
		opacity: 0.6;
	}
</style>